﻿Imports System.IO
Public Class GestionCliente
    Private listaClientes As New List(Of Cliente)
    Public ReadOnly Property Cliente As ObjectModel.ReadOnlyCollection(Of Cliente)
        Get
            Return listaClientes.AsReadOnly
        End Get
    End Property
    Private Sub ClientesIniciales()
        listaClientes.Add(New Cliente("Julen", "123456789", "yo@hotmail.com", "342534523453452 07/05"))
        Grabar()
    End Sub
    Public Sub New()
        If Not Directory.Exists("Fichero") Then
            Directory.CreateDirectory("Fichero")
        End If
        If Not File.Exists("Fichero\Clientes.txt") Then
            ClientesIniciales()
        Else
            Dim fich As StreamReader = Nothing
            Try
                fich = New StreamReader("Fichero\Clientes.txt")
                If fich.EndOfStream Then
                    ClientesIniciales()
                Else
                    Do Until fich.EndOfStream
                        Dim datos() As String
                        Dim linea As String = fich.ReadLine

                        datos = linea.Split("*")
                        listaClientes.Add(New Cliente(datos(0), datos(1), datos(2), datos(3)))

                    Loop
                    fich.Close()
                End If
            Catch ex As Exception
                fich.Close()
            End Try
        End If
    End Sub
    Private Function Grabar() As String

        Dim fic As StreamWriter = Nothing
        Try
            fic = New StreamWriter("Fichero\Clientes.txt")
            For i = 0 To listaClientes.Count - 1
                fic.WriteLine(listaClientes(i).Nombre & "*" & listaClientes(i).Password & "*" & listaClientes(i).Email & "*" & listaClientes(i).TarjetaDeCredito)

            Next
        Catch ex As Exception
            fic.Close()
            Return ex.Message
        End Try

        fic.Close()
        Return ""

    End Function
    Public Function Añadir(ByVal client As Cliente) As String
        ' Añade un nuevo producto a los existentes controlando que no existiera previamente. Si lo hace se quedará grabado en el fichero
        If client Is Nothing OrElse client.Nombre = "" OrElse client.Password = "" OrElse client.Email = "" OrElse client.TarjetaDeCredito = "" Then
            Return "Error"
        End If
        If listaClientes.Contains(client) Then

            Return "Ya existe"

        End If
        listaClientes.Add(client)
        Grabar()
        Return ""
    End Function
    Public Function Borrar(ByVal nombre As String) As String
        Dim cliente As New Cliente(nombre, "0", "0", "0")
        If Not listaClientes.Contains(cliente) Then Return "No existe"
        listaClientes.Remove(cliente)
        Grabar()
        Return ""
    End Function
End Class
